package org.footito.android.ui.activity;

import org.footito.android.R;
import org.footito.android.data.Status;
import org.footito.android.data.database.FootitoDatabaseAdapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;

public class StatusInfoActivity extends SherlockFragmentActivity {

	private static final String STATUS_ID = "statusid";
	private FootitoDatabaseAdapter dbAdapter;
	private StatusInfoFragment fragmentStatusInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getSupportActionBar().setTitle("Status");
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		dbAdapter = FootitoDatabaseAdapter.getInstance(this);
		setContentView(R.layout.activity_info_status);
		FragmentManager fragmentManager = getSupportFragmentManager();

		fragmentStatusInfo = (StatusInfoFragment) fragmentManager.findFragmentByTag(StatusInfoFragment.class
				.getSimpleName());
		if (fragmentStatusInfo == null) {
			fragmentStatusInfo = new StatusInfoFragment();
			FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
			fragmentTransaction.add(R.id.timeline_statusfragmentcontainer, fragmentStatusInfo,
					StatusInfoFragment.class.getSimpleName());
			fragmentTransaction.commit();
		}

	}

	public static void launchActivity(Context context, Status status) {
		Intent intent = new Intent(context, StatusInfoActivity.class);
		intent.putExtra(STATUS_ID, status.getId());
		context.startActivity(intent);
	}

	@Override
	protected void onResume() {
		loadStatusFromIntent();
		super.onResume();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		loadStatusFromIntent();
		super.onNewIntent(intent);
	}

	private void loadStatusFromIntent() {

		long statusId = getIntent().getExtras().getLong(STATUS_ID);
		Status status = dbAdapter.getStatus(statusId);
		fragmentStatusInfo.setStatus(status);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			finish();
		}
		return super.onOptionsItemSelected(item);
	}
}
